import os
import cPickle as pickle

def isiter(obj):
    return hasattr(obj, '__iter__')

def first_item(iter):
    ''' Returns the first item in a List, or not the input if it's not a List '''
    if isinstance(iter, list): 
        return None if not iter else iter[0]
    return iter


def walk_list(parents, L):
    ''' Convert a List to a Tree, where children are a 'list' inside L, 
        and the parent is the item to the left of the 'inside list'.
        Walks the tree, and returns (parents (list), item (object))
    '''

def is_pyfile(filepath):
    if not os.path.exists(filepath): return
    if filepath.endswith('.py'): return True
  
def flatten(L):
    new_list = []
    for item in L:
        if isiter(item):
            new_list.extend(item)
        else:
            new_list.append(item)
    return new_list
            
class TypeIter(list):
    ''' Given a list of objects that represents a branch, starting from root to the leaf.
        Finds
        Example:
            type_iter = TypeIter(shot, sequence, project)
            type_iter.Project.
    '''
    
    def __getattr__(self, name):
        for item in self:
            if item.__class__.__name__ == name:
                return item
            
def pickleable(obj):    
    try:
        pickle.dumps(obj)
        return True
    except TypeError, e:
        print str(e)
        return False